package cn.edu.csmzxy.rk233x.auth_system.security;

import cn.edu.csmzxy.rk233x.auth_system.entity.SysPermission;
import cn.edu.csmzxy.rk233x.auth_system.entity.SysRole;
import cn.edu.csmzxy.rk233x.auth_system.entity.SysUser;
import cn.edu.csmzxy.rk233x.auth_system.service.SysRolePermissionService;
import cn.edu.csmzxy.rk233x.auth_system.service.SysUserRoleService;
import cn.edu.csmzxy.rk233x.auth_system.service.SysUserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wumxing
 * @date 2025/10/15 9:56
 * @description   根据用户查询用户权限
 */

import jakarta.annotation.Resource;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysUserRoleService sysUserRoleService;

    @Resource
    private SysRolePermissionService sysRolePermissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.getByUsername(username);
        if (sysUser == null) {
            throw new UsernameNotFoundException("用户名不存在或已被锁定");
        }

        List<SysRole> roles = sysUserRoleService.getRolesByUserId(sysUser.getId());
        List<GrantedAuthority> authorities = new ArrayList<>();

        for (SysRole role : roles) {
            authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getRoleCode()));

            List<SysPermission> permissions = sysRolePermissionService.getPermissionsByRoleId(role.getId());
            List<GrantedAuthority> permissionAuthorities = permissions.stream()
                    .map(permission -> new SimpleGrantedAuthority(permission.getCode()))
                    .collect(Collectors.toList());
            authorities.addAll(permissionAuthorities);
        }

        return new org.springframework.security.core.userdetails.User(
                sysUser.getUsername(),
                sysUser.getPassword(),
                authorities
        );
    }
}
